﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;

using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Spreadsheets;

namespace DataSources.Watcher
{
    public class GoogleCells : DataSources.GoogleCells, IDataWatcher
    {
        Hashtable lastUpdateValues = new Hashtable();

        public GoogleCells(SpreadsheetsService service, GoogleWorksheets owner, string ownerCurrentEntryHash) :
            base(service, owner, ownerCurrentEntryHash)
        {
            ResetLastUpdated();
        }

        public void ResetLastUpdated()
        {
            lastUpdateValues.Clear();
            foreach (DictionaryEntry cell in cellEntries)
            {
                lastUpdateValues.Add(cell.Key, ((CellEntry)cell.Value).Value);
            }
        }

        public void RefreshLastUpdated(string entryHash, string newCacheValue)
        {
            if (newCacheValue == string.Empty)
            {
                if (lastUpdateValues.ContainsKey(entryHash))
                {
                    lastUpdateValues.Remove(entryHash);
                }
            }
            else
            {
                if (lastUpdateValues.ContainsKey(entryHash))
                {
                    lastUpdateValues[entryHash] = newCacheValue;
                }
                else
                {
                    lastUpdateValues.Add(entryHash, newCacheValue);
                }
            }
        }

        public IDataWatcher GetChildDataSource(string entryHash)
        {
            return null;
        }

        public Hashtable GetUpdatedEntries()
        {
            Hashtable updatedEntries = new Hashtable();
            foreach (DictionaryEntry cellEntry in cellEntries)
            {
                CellEntry entry = (CellEntry)cellEntry.Value;
                if (lastUpdateValues.ContainsKey(cellEntry.Key))
                {
                    if (entry.Value != lastUpdateValues[cellEntry.Key] as string)
                    {
                        // track changed
                        updatedEntries.Add(cellEntry.Key, cellEntry.Value);
                    }
                }
                else
                {
                    // track added
                    updatedEntries.Add(cellEntry.Key, cellEntry.Value);
                }
            }
            foreach (DictionaryEntry cellEntry in lastUpdateValues)
            {
                if (!cellEntries.ContainsKey(cellEntry.Key))
                {
                    // track removed
                    updatedEntries.Add(cellEntry.Key, cellEntry.Value);
                }
            }
            return updatedEntries;
        }
    }
}
